const btn = document.querySelector(".btn");
const datas = new Array(100000).fill(0).map((_, i) => i);
btn.onclick = () => {
  const taskHandler = (i) => {
    const div = document.createElement("div");
    div.innerText = i;
    document.body.appendChild(div);
  };
  const scheduler = (task) => {
    setTimeout(() => {
      const now = performance.now();
      task(() => {
        performance.now() - now <= 10;
      });
    }, 1000);
  };
  performChunk(datas, taskHandler, scheduler);
  //   浏览器环境
  //   browserPerformChunk(100000, taskHandler, scheduler);
};

function performChunk(datas, taskHandler, scheduler) {
  if (typeof datas === "number") {
    datas = {
      length: datas,
    };
  }
  if (datas.length === 0) return;
  let i = 0;
  // 开启下一个分片的执行
  function _run() {
    if (i >= datas.length) {
      return;
    }
    // 一个渲染中，空闲时开启分片执行
    scheduler((gonOn) => {
      while (gonOn() && i < datas.length) {
        taskHandler(datas[i], i);
        i++;
      }
    });
    // 此次分片完成
    _run();
  }
  _run();
}

function browserPerformChunk(datas, taskHandler) {
  const scheduler = (task) => {
    requestIdleCallback((idle) => {
      task(() => idle.timeRemaining());
    });
  };
  performChunk(datas, taskHandler, scheduler);
}
